package com.zhentao.datacontrol.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.datacontrol.domain.entity.ExecutionLog;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

@Mapper
public interface ExecutionLogMapper extends BaseMapper<ExecutionLog> {

    /**
     * 分页查询执行记录（带规则信息）
     */
    @Select("<script>" +
            "SELECT l.*, r.rule_name " +
            "FROM dc_execution_log l " +
            "LEFT JOIN dc_rule r ON l.rule_id = r.id " +
            "WHERE 1=1 " +
            "<if test='executionType != null and executionType != \"\"'> AND l.execution_type = #{executionType} </if>" +
            "<if test='executionStatus != null and executionStatus != \"\"'> AND l.execution_status = #{executionStatus} </if>" +
            "ORDER BY l.created_time DESC" +
            "</script>")
    IPage<ExecutionLog> selectPageWithRule(Page<ExecutionLog> page,
                                         @Param("executionType") String executionType,
                                         @Param("executionStatus") String executionStatus);

    /**
     * 根据执行ID查询执行记录
     */
    @Select("SELECT l.*, r.rule_name FROM dc_execution_log l " +
            "LEFT JOIN dc_rule r ON l.rule_id = r.id " +
            "WHERE l.execution_id = #{executionId}")
    ExecutionLog selectByExecutionId(@Param("executionId") String executionId);

    /**
     * 查询最近的执行记录
     */
    @Select("SELECT l.*, r.rule_name FROM dc_execution_log l " +
            "LEFT JOIN dc_rule r ON l.rule_id = r.id " +
            "ORDER BY l.created_time DESC " +
            "LIMIT #{limit}")
    List<ExecutionLog> selectRecentLogs(@Param("limit") int limit);

    /**
     * 更新执行状态
     */
    @Update("UPDATE dc_execution_log SET execution_status = #{status}, " +
            "end_time = #{endTime}, duration_seconds = #{durationSeconds}, " +
            "error_message = #{errorMessage} " +
            "WHERE execution_id = #{executionId}")
    int updateExecutionStatus(@Param("executionId") String executionId,
                            @Param("status") String status,
                            @Param("endTime") String endTime,
                            @Param("durationSeconds") Integer durationSeconds,
                            @Param("errorMessage") String errorMessage);

    /**
     * 更新执行统计
     */
    @Update("UPDATE dc_execution_log SET " +
            "total_records = #{totalRecords}, " +
            "checked_records = #{checkedRecords}, " +
            "error_records = #{errorRecords}, " +
            "warning_records = #{warningRecords} " +
            "WHERE execution_id = #{executionId}")
    int updateExecutionStatistics(@Param("executionId") String executionId,
                                @Param("totalRecords") Integer totalRecords,
                                @Param("checkedRecords") Integer checkedRecords,
                                @Param("errorRecords") Integer errorRecords,
                                @Param("warningRecords") Integer warningRecords);

    /**
     * 查询执行统计
     */
    @Select("SELECT " +
            "COUNT(*) as total_executions, " +
            "SUM(CASE WHEN execution_status = 'SUCCESS' THEN 1 ELSE 0 END) as success_count, " +
            "SUM(CASE WHEN execution_status = 'FAILED' THEN 1 ELSE 0 END) as failed_count, " +
            "SUM(CASE WHEN execution_status = 'RUNNING' THEN 1 ELSE 0 END) as running_count " +
            "FROM dc_execution_log " +
            "WHERE created_time >= #{startDate}")
    ExecutionLog getExecutionStatistics(@Param("startDate") String startDate);

    /**
     * 清理历史记录
     */
    @Update("DELETE FROM dc_execution_log WHERE created_time < #{beforeDate}")
    int cleanHistoryBefore(@Param("beforeDate") String beforeDate);
}
